package activities;

import simpleDB.DatabaseHelper;
import simpleDB.PersonDataObject;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.example.intellifit.R;

public class SettingsNewActivity extends Activity {

	private final int weigth_min = 50;
	private final int weigth_max = 130;
	private final int height_min = 150;
	private final int height_max = 210;
	private RadioButton radio0,radio1,radio2;

	private int weight_old = weigth_min;
	private int height_old = height_min;
	private Button pickDateBtn, saveBtn;
	private SeekBar seekbarHeight, seekbarWeight;
	private EditText editTextWeight, editTextHeight, editTextPerson;
	static final int DATE_DIALOG_ID = 0;
	private int mYear, mMonth, mDay;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_settings_new);
		// Show the Up button in the action bar.
		setupActionBar();
		init();
	}

	private void init() {
		saveBtn = (Button) findViewById(R.id.saveBtn);
		radio0 = (RadioButton) findViewById(R.id.radio0);
		radio1 = (RadioButton) findViewById(R.id.radio1);
		radio2 = (RadioButton) findViewById(R.id.radio2);

		// DATE-Picker
		pickDateBtn = (Button) findViewById(R.id.pickDate);
//		saveBtn = (Button) findViewById(R.id.saveBtn);
		pickDateBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showDialog(DATE_DIALOG_ID);
			}
		});

		updateDisplay();

		// Height-Seekbar
		editTextHeight = (EditText) findViewById(R.id.editTextHeight);
		seekbarHeight = (SeekBar) findViewById(R.id.seekBarHeight);

		editTextHeight.setOnFocusChangeListener(new OnFocusChangeListener() {

			public void onFocusChange(View v, boolean hasFocus) {
				if (!hasFocus) {
					height_old = revertEditText(editTextHeight, height_old,
							height_min, height_max);
					seekbarHeight.setProgress(calcSeekbarFromNr(height_min,
							height_max, height_old));
				}

			}
		});

		editTextHeight
				.setOnEditorActionListener(new TextView.OnEditorActionListener() {
					@Override
					public boolean onEditorAction(TextView v, int actionId,
							KeyEvent event) {
						if (actionId == EditorInfo.IME_ACTION_DONE) {
							height_old = revertEditText(editTextHeight,
									height_old, height_min, height_max);
							seekbarHeight.setProgress(calcSeekbarFromNr(
									height_min, height_max, height_old));
							return true;
						}
						return false;
					}
				});

		seekbarHeight = (SeekBar) findViewById(R.id.seekBarHeight);
		seekbarHeight.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				editTextHeight.setText(calcNrFromSeekbar(height_min,
						height_max, progress) + "");
			}
		});

		// Weight-Seekbar
		editTextWeight = (EditText) findViewById(R.id.editTextWeight);
		editTextWeight.setOnFocusChangeListener(new OnFocusChangeListener() {

			public void onFocusChange(View v, boolean hasFocus) {
				if (!hasFocus) {
					weight_old = revertEditText(editTextWeight, weight_old,
							weigth_min, weigth_max);
					seekbarWeight.setProgress(calcSeekbarFromNr(weigth_min,
							weigth_max, weight_old));
				}

			}
		});

		editTextWeight
				.setOnEditorActionListener(new TextView.OnEditorActionListener() {
					@Override
					public boolean onEditorAction(TextView v, int actionId,
							KeyEvent event) {
						if (actionId == EditorInfo.IME_ACTION_DONE) {
							weight_old = revertEditText(editTextWeight,
									weight_old, weigth_min, weigth_max);
							seekbarWeight.setProgress(calcSeekbarFromNr(
									weigth_min, weigth_max, weight_old));
							return true;
						}
						return false;
					}
				});

		seekbarWeight = (SeekBar) findViewById(R.id.seekBarWeight);
		seekbarWeight.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				editTextWeight.setText(calcNrFromSeekbar(weigth_min,
						weigth_max, progress) + "");
			}
		});

		// Weight-Edittext-Listener
		// editTextWeight.setOnKeyListener(this);
		
				
		// get DB values
		PersonDataObject pdo = new PersonDataObject();
		DatabaseHelper dbHelper = new DatabaseHelper(this);
		try {
			pdo = dbHelper.getPerson(1);
		} catch (Exception exc) {
			pdo.birthdate = "2-2-1980";
			pdo.height = 170;
			pdo.weight = 84;
			pdo.level = 0;
			pdo.name = "Otto Normalverbraucher";
		}
		editTextPerson = (EditText) findViewById(R.id.editText1);
		
		editTextPerson.setText(pdo.name);
		editTextHeight.setText(pdo.height+"");
		editTextWeight.setText(pdo.weight+"");
		
		weight_old = pdo.weight;
		height_old = pdo.height;
		
		String[] sep = pdo.birthdate.split("-");
		mDay = Integer.parseInt(sep[0]);
		mMonth = Integer.parseInt(sep[1]);
		mYear = Integer.parseInt(sep[2]);
		updateDisplay();
		
		switch (pdo.level) {
		case 0:
			radio0.setChecked(true);
			break;
		case 1:
			radio1.setChecked(true);
			break;
		

		default:
			radio2.setChecked(true);
		}
		
		seekbarHeight.setProgress(calcSeekbarFromNr(height_min,
				height_max, height_old));
		seekbarWeight.setProgress(calcSeekbarFromNr(weigth_min,
				weigth_max, weight_old));
	    
//		

		saveBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				save();
			}
		});
	}

	private void save() {
		Toast.makeText(this, "New settings saved !", Toast.LENGTH_SHORT).show();
		PersonDataObject pdo = new PersonDataObject();
		pdo.name = editTextPerson.getText().toString();
		pdo.height = Integer.parseInt(editTextHeight.getText().toString());
		pdo.weight = Integer.parseInt(editTextWeight.getText().toString());
		pdo.birthdate = pickDateBtn.getText().toString();
		pdo.birthdate = pdo.birthdate.substring(0,pdo.birthdate.length() -1 );
		
		int level;
		if (radio0.isChecked()) {
			level = 0;
		} else if (radio1.isChecked()) {
			level = 1;
		} else {
			level = 2;
		}
		
		pdo.level = level;
		pdo.id = 1;
		DatabaseHelper dbHelper = new DatabaseHelper(this);
		dbHelper.addPerson(pdo);
	}
	
	
	/**
	 * Set up the {@link android.app.ActionBar}.
	 */
	private void setupActionBar() {

		getActionBar().setDisplayHomeAsUpEnabled(true);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.settings_new, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	/* Date */
	// updates the date in the TextView
	private void updateDisplay() {
		pickDateBtn.setText(getString(R.string.strSelectedDate,
				new StringBuilder()
						// Month is 0 based so add 1
						.append(mDay).append("-").append(mMonth + 1)
						.append("-").append(mYear).append(" ")));
	}

	// the callback received when the user "sets" the date in the dialog
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;
			updateDisplay();
		}
	};

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
					mDay);
		}
		return null;
	}

	/* Date */

	private int calcNrFromSeekbar(int min, int max, int progress) {
		return min + ((max - min) * progress / 100);
	}

	private int calcSeekbarFromNr(int min, int max, int nr) {
		if (nr == min) {
			return 0;
		}
		int range = max - min; // 70
		int val = nr - min; // 40
		float perc = ((float) val / (float) range) * 100;
		return (int) perc + 1;
	}

	public int revertEditText(EditText edt, int oldval, int min, int max) {
		int newval;
		if (edt.getText().toString().equals("")) {
			newval = 0;
		} else {
			newval = Integer.parseInt(edt.getText().toString());
		}
		if (newval < min || newval > max) {
			edt.setText(oldval + "");
			Toast.makeText(this, "Range: " + min + " .. " + max,
					Toast.LENGTH_SHORT).show();
			return oldval;
		} else {
			return newval;
		}
	}
}
